
import cookies from 'js-cookie'
import http from "./req";
import router from "../router";


let userService = {
    currentUser : null,
    hasUserLogin(){
        return this.currentUser;
    },

    isAdmin(){
        return this.currentUser && this.currentUser.type === 3;
    },

    isLeader(){
        return this.currentUser && this.currentUser.type === 2;
    },

    isResearcher(){
        return this.currentUser && this.currentUser.type === 1;
    },


    setCurrentUser(user, expires= null){
        this.currentUser = user;
        if (user)
            sessionStorage.setItem("c_user", JSON.stringify(user))
        else {
            sessionStorage.clear()
        }
    },

    refreshCurrentUser(){
        this.currentUser = JSON.parse(sessionStorage.getItem("c_user"));
        http.get('/user/profile').then((res => {
            let data = res.data.data;
            if (res.data.code === 200) {
                this.setCurrentUser(data)
            }else if (res.data.code === 401){
                this.currentUser = null;
                sessionStorage.removeItem("c_user");
            }
        }))
    }
}

userService.refreshCurrentUser();

export default userService